package ltd.newbee.mall.config;

import com.fasterxml.classmate.GenericType;
import com.fasterxml.classmate.TypeResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.schema.AlternateTypeRules;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import java.lang.reflect.WildcardType;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Configuration //标记为配置类，启动时加载这个类
@EnableSwagger2 //此项目使用Swagger API文档
public class Swagger2Config {
    @Resource
    private TypeResolver typeResolver;

    @Bean
    public Docket api() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //指定要扫描的控制器包路径，这个路径下的类才会自动生成Swagger API文档
                //注意大小写要和实际保持一致
                .apis(RequestHandlerSelectors.basePackage("ltd.newbee.mall.controller"))
                .paths(PathSelectors.any())
                .build();

        //List<Integer> 类型就是如下表示
        //ResolvedType type = TypeResolver.resolve(List.class, Integer.class);

        //复杂类型需要配置：Map<String, Map<String, List<String>>>
        //map是双参数的
        docket.alternateTypeRules(
                AlternateTypeRules.newRule(
                        typeResolver.resolve(Map.class, String.class,
                                typeResolver.resolve(Map.class, String.class, typeResolver.resolve(List.class, String.class))),
                        typeResolver.resolve(Map.class, String.class, WildcardType.class), Ordered.HIGHEST_PRECEDENCE
                ));
        //复杂类型需要配置：List<Map<String, Object>>
        //List 是单参数的
        docket.alternateTypeRules(
                AlternateTypeRules.newRule(
                        typeResolver.resolve(List.class,
                                typeResolver.resolve(Map.class, String.class, Object.class)),
                        typeResolver.resolve(List.class, WildcardType.class), Ordered.HIGHEST_PRECEDENCE
                ));

        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger-api文档") //标题
                .description("swagger文档by13") //描述
                .version("1.0") //版本
                .build();
    }
}
